#include<stdio.h>
#include<string.h>
#include"sm4.h"
#include<string.h>
#include <stdlib.h>
size_t __real_fwrite(const void*buffer,size_t size,size_t count,FILE*stream);
FILE* __real_fopen(const char * path,const char * mode);
size_t __real_fread(void *ptr, size_t size,size_t nitems, FILE *stream);
size_t  __real_fseek( FILE *stream, long offset, int origin );
unsigned char key[16]={"1234567890123456"};


size_t  __wrap_fwrite(const void*buffer,size_t size,size_t count,FILE*stream)
{
sm4_context ctx;
int length;
if(size%16!=0)
   length=(size/16+1)*16;
else
   length=size;
printf("%d",length);
unsigned char *output=(unsigned char*)alloca(length);
unsigned char *input=(unsigned char*)alloca(length);
memcpy(input,buffer,length);  
sm4_setkey_enc(&ctx, key); //设置秘钥
sm4_crypt_ecb(&ctx, 0, length, input, output); //加密
sm4_crypt_ecb(&ctx, 0, length, output, input); //加密
printf("MY WRITING: \n");
return __real_fwrite(output,length,count,stream);
}
FILE* __wrap_fopen(const char * path,const char * mode)
{
      FILE *pFile = __real_fopen(path,mode);
      printf("MY OPEN: \n");
      return pFile;
}
size_t __wrap_fread(void *ptr, int size, int nitems, FILE *stream)
{
     int length;
     if(size%16!=0)
         length=(size/16+1)*16;
     else
         length=size;
     printf("MY READ: \n");
     unsigned char *input=(unsigned char*)alloca(length);
     unsigned char *output=(unsigned char*)malloc(length);
     size_t result= __real_fread(input,length,nitems,stream);
     sm4_context ctx;
     sm4_setkey_dec(&ctx, key); //设置秘钥,与加密过程唯一不同的地方
     sm4_crypt_ecb(&ctx, 0, length, input, output); //解密
     memcpy(ptr,output,length);  
     return result;
}
size_t __wrap_fseek( FILE *stream, long offset, int origin )
{
  printf("MY FSEEK\n");
  return __real_fseek(stream,offset,origin );
}

